package com.lagou.task.servlet;

import com.lagou.task.entity.Student;
import com.lagou.task.service.StudentService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "StudentShowServlet",urlPatterns = "/add")
public class StudentAddServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置编码格式
        request.setCharacterEncoding("UTF-8");
        // 获取参数并创建对象
        String studentId = request.getParameter("id");
        String studentName = request.getParameter("name");
        String studentSex = request.getParameter("sex");
        String studentBirth = request.getParameter("birth");
        String studentEmail = request.getParameter("email");
        String studentNote = request.getParameter("note");
        Student student = new Student(studentId,studentName,studentSex,studentBirth,studentEmail,studentNote);
        //System.out.println(student);
        // 添加学生信息服务
        StudentService studentService = new StudentService();
        int i = studentService.addStudentService(student);
        if (i == 1){
            response.sendRedirect("show.jsp");
            if (request.getAttribute("addError") != null){
                request.removeAttribute("addError");
            }
        }else {
            request.setAttribute("addError","addError");
            // 实现服务器跳转  共享request和response对象
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("show.jsp");
            requestDispatcher.forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
